package com.lxl.bt.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.JsonObject;
import com.lxl.bt.R;
import com.lxl.bt.bean.CustomViewsInfo;
import com.lxl.bt.bean.DianliBean;
import com.lxl.bt.bean.ProductBean;
import com.lxl.bt.fragment.DetailArgumentsFragment;
import com.lxl.bt.fragment.IOnWebViewTouch;
import com.lxl.bt.fragment.ProductDetailHintFragment;
import com.lxl.bt.net.NetApi;
import com.lxl.bt.net.Result;
import com.lxl.bt.retorfit.NetCallback;
import com.lxl.bt.retorfit.RetrofitUtil;
import com.lxl.bt.util.ACache;
import com.lxl.bt.util.GlideUtils;
import com.lxl.bt.view.CustomViewPager;
import com.stx.xhb.androidx.XBanner;
import com.yanzhenjie.sofia.Sofia;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Create by lvxinlong
 * on  产品详情
 * on  2021年3月5日22:55:32
 **/
public class ProductDetailActivity extends BaseActivity implements IOnWebViewTouch {


    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.rlBack)
    RelativeLayout rlBack;
    @BindView(R.id.txt_toolbar_title)
    TextView txtToolbarTitle;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.tvRight)
    TextView tvRight;
    @BindView(R.id.rlRight)
    RelativeLayout rlRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tab_layout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.view_pager)
    CustomViewPager viewPager;
    @BindView(R.id.banner)
    XBanner banner;
    @BindView(R.id.tvDateLong)
    TextView tvDateLong;
    @BindView(R.id.tvStart)
    TextView tvStart;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.tvGjprice)
    TextView tvGjprice;
    @BindView(R.id.tvSuanli)
    TextView tvSuanli;
    @BindView(R.id.tvDianfei)
    TextView tvDianfei;
    @BindView(R.id.tvLirun)
    TextView tvLirun;
    @BindView(R.id.tvZhouqi)
    TextView tvZhouqi;
    @BindView(R.id.tvCommit)
    TextView tvCommit;
    @BindView(R.id.rcv)
    RecyclerView rcv;
    @BindView(R.id.ll_df)
    View df;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.tv_text_1)
    TextView tvText1;
    @BindView(R.id.tv_text_2)
    TextView tvText2;
    @BindView(R.id.tv_text_3)
    TextView tvText3;
    @BindView(R.id.tv_text_4)
    TextView tvText4;
    @BindView(R.id.tv_text_5)
    TextView tvText5;

    private Context context;
    ACache aCache;
    FragmentAdapter fragmentAdapter;
    private int current;
    ProductBean product;
    private String[] titles = {"算力参数", "其他信息", "风险提示"};
    private ArrayList<DianliBean> dianlist;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    BaseQuickAdapter<DianliBean, BaseViewHolder> sysAdapter;
    private int selected = 0;

    @Override
    public void onWebViewTouch(boolean isTouch) {
        scrollView.requestDisallowInterceptTouchEvent(isTouch);
        viewPager.requestDisallowInterceptTouchEvent(isTouch);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_productdetail);
        ButterKnife.bind(this);
        //状态栏全透明全屏显示页面，布局能够延伸到状态栏和导航栏下方
        Sofia.with(this)
                .invasionStatusBar()
                .statusBarLightFont()
//                .statusBarDarkFont()
                .statusBarBackgroundAlpha(0)
                .invasionNavigationBar()
                .navigationBarBackgroundAlpha(0);

        context = this;
        rlBack.setVisibility(View.VISIBLE);
        txtToolbarTitle.setText("产品详情");
        rlRight.setVisibility(View.GONE);
        aCache = ACache.get(this);
        product = (ProductBean) getIntent().getSerializableExtra("data");
        initBanner();

        tvStart.setText(product.getStartDate());
        tvEndTime.setText(product.getEndDate());

        if ("1".equals(product.getType())){//type = 1
            tvDateLong.setText("永久");
            tvGjprice.setText("¥ " + product.getPrice() + (isKuangJi() ? "/台" : "/份"));
            tvSuanli.setText(product.getPower() + "T/台");
            tvDianfei.setText(product.getElectricPrice() + "/天/台");
            tvLirun.setText(product.getProOut());
            tvZhouqi.setText(product.getDateLong() + "天");
        }else{//type = 0
            tvText1.setText("每T价格");
            tvDateLong.setText(product.getDateLong() + "天产权");
            tvGjprice.setText("¥ " + product.getPrice() + "+" + product.fileNumBerT + "FIL");
            tvText2.setText("套餐算力");
            tvSuanli.setText(product.getPower() + "T/份");
            tvText3.setText("套餐电费");
            tvDianfei.setText(product.getElectricPrice());

            tvText4.setText("理论产出");
            tvLirun.setText(product.getProOut());
            tvText5.setText("预计：年所得率");
            tvZhouqi.setText(product.getYearRate());
        }

        fragments.clear();
        fragments.add(DetailArgumentsFragment.newInstance(product));
        fragments.add(ProductDetailHintFragment.newInstance(1, product.getOtherCommtents()));
        fragments.add(ProductDetailHintFragment.newInstance(2, product.getWarningTips()));
        sysAdapter = new BaseQuickAdapter<DianliBean, BaseViewHolder>(R.layout.item_dianli) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, DianliBean bean) {
            }


            @Override
            public void onBindViewHolder(@NonNull BaseViewHolder baseViewHolder, int position) {
                baseViewHolder.setText(R.id.tvDays, getItem(position).getDateStr() + "天");
                baseViewHolder.setText(R.id.tvPrice, "￥" + getItem(position).getAmount());
                baseViewHolder.setTextColor(R.id.tvDays, selected == position ? getResources().getColor(R.color.black) : getResources().getColor(R.color.cffffff));
                baseViewHolder.setTextColor(R.id.tvPrice, selected == position ? getResources().getColor(R.color.black) : getResources().getColor(R.color.cffffff));
                baseViewHolder.setBackgroundColor(R.id.llroot, selected == position ? getResources().getColor(R.color.colorMain) : getResources().getColor(R.color.c63));

            }
        };
        rcv.setAdapter(sysAdapter);
        sysAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                selected = position;
                sysAdapter.setNewData(sysAdapter.getData());
            }
        });

        initView();
        refFragmentView();
        getList();
    }

    private void initView() {
        df.setVisibility(isKuangJi() ? View.VISIBLE : View.GONE);
    }

    private boolean isKuangJi() {
        return product.getType().equals("1");
    }

    private void initBanner() {
        List<CustomViewsInfo> data = new ArrayList<>();
        data.add(new CustomViewsInfo(product.getBannerUrl()));
        banner.setBannerData(R.layout.layout_custom_view, data);
        banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                ImageView iv = (ImageView) view.findViewById(R.id.iv);
//                iv.setImageResource(R.mipmap.banner3);
                GlideUtils.loadImage(iv, product.getBannerUrl());
            }
        });
        banner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {
            }
        });
    }

    void refFragmentView() {
        fragmentAdapter = new FragmentAdapter(getSupportFragmentManager());
        viewPager.setAdapter(fragmentAdapter);
        tabLayout.setViewPager(viewPager);
        viewPager.setCurrentItem(current);
        viewPager.setOffscreenPageLimit(titles.length);


        refTableTitleView();
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                current = position;
                refTableTitleView();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void refTableTitleView() {
        for (int i = 0; i < titles.length; i++) {
            if (i == current) {
                tabLayout.getTitleView(current).getPaint().setFakeBoldText(true);
            } else {
                tabLayout.getTitleView(i).getPaint().setFakeBoldText(false);
            }
        }


    }

    public void getList() {
        // 类型：0云矿机，1：实体矿机
        if (product.getType().equals("0")) return;
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("pageNo", 1);
        jsonObject.addProperty("pageSize", 20);
        RetrofitUtil.getInstance().create(NetApi.class, 0)
                .getLightPakeage(product.getProductId()).enqueue(new NetCallback<Result<ArrayList<DianliBean>>>() {
            @Override
            public void onSuccess(Result<ArrayList<DianliBean>> result) {
                if (result.isSuccess()) {
                    sysAdapter.setNewData(result.getData());
                }
            }

            @Override
            public void netLogin() {

            }

            @Override
            public void onError(String errorStr) {
                super.onError(errorStr);
                Log.w("lxl", errorStr);

            }

        });
    }

    @OnClick({R.id.rlBack, R.id.tvCommit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlBack:
                finish();
                break;
            case R.id.tvCommit:
//                new CustomCommonDialog.Builder(ProductDetailActivity.this, false, true, true, Gravity.BOTTOM)
//                        .buyDialog(product, sysAdapter.getItem(selected), new AlertCallback() {
//                            @Override
//                            public void doConfirm(Object... args) {
//                                super.doConfirm(args);
//                                CreateOrderBody order = (CreateOrderBody) args[0];
//                                ToastUtils.s(ProductDetailActivity.this, "创建成功");
//
//                            }
//                        }).show();
                PayActivity.Companion.start(view.getContext(),sysAdapter.getItem(selected),product);
                break;
        }
    }


    private class FragmentAdapter extends FragmentStatePagerAdapter {
        //        private String[] titles;
        public FragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
//            return ProductDetailHintFragment.newInstance(position);
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }
    }
}
